package org.jeecg.modules.demo.weixin.douyin.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.demo.weixin.douyin.config.DYConfig;
import org.jeecg.modules.demo.weixin.douyin.vo.CheckTicketVo;
import org.jeecg.modules.demo.weixin.douyin.vo.OrderStatusVo;
import org.jeecg.modules.demo.weixin.douyin.vo.VerifyResultsVo;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class DouYinUtil {


    private static RedisUtil redisUtil;

    @Resource
    public void setRedisUtil(RedisUtil redisUtil) {
        DouYinUtil.redisUtil = redisUtil;
    }

    public static String auth() throws Exception {
        //获取redis
        Object accessToken = redisUtil.get("dyClientToken");
        if (accessToken == null) {
            //存redis
            JSONObject paramMap = new JSONObject();
            paramMap.put("client_key", DYConfig.ClientKey);
            paramMap.put("client_secret", DYConfig.ClientSecret);
            paramMap.put("grant_type", "client_credential");
            String result = HttpUtil.post(DYConfig.dyClientToken, paramMap);
            JSONObject resultBody = JSONObject.parseObject(result);
            log.info("请求临时token接口返回参数：" + resultBody);
            if (!resultBody.getJSONObject("data").get("error_code").equals(0)) {
                return null;
            }
            //获取返回值的临时code
            redisUtil.set("dyClientToken", resultBody.getJSONObject("data").get("access_token"), 7200);
            accessToken = redisUtil.get("dyClientToken");
        }
        log.info("无需授权临时token=" + accessToken);
        return (String) accessToken;
    }


    /**
     * 检验券
     *
     * @return
     * @throws Exception
     */
    public static CheckTicketVo examine(String token, String code,String encrypteData) throws Exception {
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.hasText(code)){
            jsonObject.put("code", code);
        }
        if (StringUtils.hasText(encrypteData)) {
            String encrypte = HttpUtil.get(encrypteData);
            String encrypteCode = encrypte.substring(encrypte.indexOf("object_id") + 10).split("&")[0];
            jsonObject.put("encrypted_data", encrypteCode);
        }
        //调用验券准备接口
        String result = HttpRequest.get(DYConfig.dyCheck).contentType("application/json").header("access-token", token).form(jsonObject).execute().body();
        JSONObject resultBody = JSONObject.parseObject(result);
        CheckTicketVo checkTicket = new CheckTicketVo();
        //判断返回是否是0--success
        if (!resultBody.getJSONObject("data").get("error_code").equals(0)) {
            return null;
        }

        //判断可用团购券列表是否为空
        if (CollectionUtils.isEmpty(resultBody.getJSONObject("data").getJSONArray("certificates"))) {
            return null;
        }
        //获取数据并填写  主要（.verify_token 一次验券的标识, 在验券接口传入    encrypted_code券码加密 )  order_id  订单id等
        checkTicket.setVerifyToken(resultBody.getJSONObject("data").getString("verify_token"));
        checkTicket.setOrderId(resultBody.getJSONObject("data").getString("order_id"));
        checkTicket.setEncryptedCode(resultBody.getJSONObject("data").getJSONArray("certificates").getJSONObject(0).getString("encrypted_code"));
        checkTicket.setCertificateId(resultBody.getJSONObject("data").getJSONArray("certificates").getJSONObject(0).getString("certificate_id"));
        checkTicket.setStartTime(resultBody.getJSONObject("data").getJSONArray("certificates").getJSONObject(0).getLong("start_time"));
        checkTicket.setExpireTime(resultBody.getJSONObject("data").getJSONArray("certificates").getJSONObject(0).getLong("expire_time"));
        checkTicket.setPayAmount(resultBody.getJSONObject("data").getJSONArray("certificates").getJSONObject(0).getJSONObject("amount").getInteger("pay_amount"));
        checkTicket.setOriginalAmount(resultBody.getJSONObject("data").getJSONArray("certificates").getJSONObject(0).getJSONObject("amount").getInteger("original_amount"));
        checkTicket.setListMarketAmount(resultBody.getJSONObject("data").getJSONArray("certificates").getJSONObject(0).getJSONObject("amount").getInteger("list_market_amount"));
        checkTicket.setCouponPayAmount(resultBody.getJSONObject("data").getJSONArray("certificates").getJSONObject(0).getJSONObject("amount").getInteger("coupon_pay_amount"));
        checkTicket.setTitle(resultBody.getJSONObject("data").getJSONArray("certificates").getJSONObject(0).getJSONObject("sku").getString("title"));
        checkTicket.setSkuId(resultBody.getJSONObject("data").getJSONArray("certificates").getJSONObject(0).getJSONObject("sku").getString("sku_id"));
        checkTicket.setAccountId(resultBody.getJSONObject("data").getJSONArray("certificates").getJSONObject(0).getJSONObject("sku").getString("account_id"));
        checkTicket.setGrouponType(resultBody.getJSONObject("data").getJSONArray("certificates").getJSONObject(0).getJSONObject("sku").getInteger("groupon_type"));
        //如果类型是3次卡   获取总次数以及使用次数
        if (checkTicket.getGrouponType().equals(3)) {
            checkTicket.setTimesCount(resultBody.getJSONObject("data").getJSONArray("certificates").getJSONObject(0).getJSONObject("time_card").getInteger("times_count"));
            checkTicket.setTimesUsed(resultBody.getJSONObject("data").getJSONArray("certificates").getJSONObject(0).getJSONObject("time_card").getInteger("times_used"));
        }

        return checkTicket;
    }

    /**
     * 订单查询接口
     * @param token
     * @param orderId
     * @param accountId
     * @param page
     * @param size
     * @return
     * @throws Exception
     */
    public static List<OrderStatusVo> queryOrder(String token, String orderId, String accountId, Integer page, Integer size) throws Exception {
        log.info("请求参数：token:"+token+"订单id" + orderId + "账号" + accountId + " 第几页：" + page + "页数：" + size);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("account_id", accountId);
        jsonObject.put("page_num", page);
        jsonObject.put("page_size", size);
//        jsonObject.put("order_status", 201);
        jsonObject.put("order_id", orderId);
//        jsonObject.put("open_id", req.getOrderId());
//        jsonObject.put("create_order_start_time", 169712048559L);
//        jsonObject.put("create_order_end_time", System.currentTimeMillis());
        String result = HttpRequest.get(DYConfig.dyQueryOrder).contentType("application/json").header("access-token", token).form(jsonObject).execute().body();
        JSONObject resultBody = JSONObject.parseObject(result);
        if (!resultBody.getJSONObject("data").get("error_code").equals(0)) {
            return null;
        }
        //获取订单信息 状态
        JSONArray orderStatusJSONArray = resultBody.getJSONObject("data").getJSONArray("orders").getJSONObject(0).getJSONArray("certificate");
        JSONArray namePhone = resultBody.getJSONObject("data").getJSONArray("orders").getJSONObject(0).getJSONArray("contacts");
        List<OrderStatusVo> orderStatusVoList = orderStatusJSONArray.stream().map(item -> JSON.parseObject(((JSONObject) item).toString(), OrderStatusVo.class)).collect(Collectors.toList());
        orderStatusVoList.forEach(orderStatusVo -> {
            orderStatusVo.setDyPhone(namePhone.getJSONObject(0).getString("phone"));
            orderStatusVo.setUserName(namePhone.getJSONObject(0).getString("name"));
            orderStatusVo.setPhoneEncrypt(namePhone.getJSONObject(0).getString("phone_encrypt"));
        });
        return orderStatusVoList;
    }



    public static VerifyResultsVo verification( String token,String encryptedCode,String verifyToken ,String poiId) throws Exception {
        log.info("请求参数：" + encryptedCode+"唯一标示："+verifyToken+"商家id:"+poiId+"token:"+token);
        //调用核销接口
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("verify_token", verifyToken);
        jsonObject.put("poi_id", poiId);
//        jsonObject.put("order_id", req.getOrderId());
        JSONArray encryptedCodeArray = new JSONArray();
        encryptedCodeArray.add(encryptedCode);
//        jsonObject.put("code_with_time_list", encryptedCodeArray);
        jsonObject.put("encrypted_codes", encryptedCodeArray);

        log.info("调用核销接口参数：" + jsonObject);
        String result = HttpRequest.post(DYConfig.dyVerify).contentType("application/json").header("access-token", token).body(jsonObject.toJSONString()).execute().body();
        JSONObject resultBody = JSONObject.parseObject(result);
        //判断返回是否是0--success
        Integer errorCode = resultBody.getJSONObject("data").getInteger("error_code");
        Integer errorResult = resultBody.getJSONObject("data").getJSONArray("verify_results").getJSONObject(0).getInteger("result");
        if ((!errorCode.equals(0)) && (!errorResult.equals(0))) {
            //不等于0    进行下一阶段校验
            if (errorCode.equals(1208) || errorResult.equals(2)) {
                VerifyResultsVo verify = JSON.parseObject(resultBody.getJSONObject("data").getJSONArray("verify_results").getJSONObject(0).toString(), VerifyResultsVo.class);
                return verify;
            }
            return null;

        }
        VerifyResultsVo verifyResults = JSON.parseObject(resultBody.getJSONObject("data").getJSONArray("verify_results").getJSONObject(0).toString(), VerifyResultsVo.class);
        return verifyResults;
    }


    public static Boolean chexiao(String token,String verifyId, String certificateId){
        log.info("请求参数：核销的唯一标识:"+verifyId+"代表一张券码的标识:"+certificateId+"token:"+token);
        //调用核销接口
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("verify_id", verifyId);
        jsonObject.put("certificate_id", certificateId);
        log.info("撤销接口：" + jsonObject);
        String result = HttpRequest.post(DYConfig.dyChexiao).contentType("application/json").header("access-token", token).body(jsonObject.toJSONString()).execute().body();
        JSONObject resultBody = JSONObject.parseObject(result);
        //判断返回是否是0--success
      if (!resultBody.getJSONObject("data").get("error_code").equals(0)) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }


}
